﻿Imports ImageManipulation
Public MustInherit Class ImageCommandBase
    Inherits CommandBase
    Protected g As Graphics
    Protected b As Bitmap
    Private previousbytes() As Byte
    Protected _imagename As String
    Public Sub New(ByVal ImageName As String)
        _imagename = ImageName
    End Sub
    Protected MustOverride Sub ExecuteCommand()
    Protected Sub SaveBitmap()
        Dim extension As String = Path.GetExtension(_imagename)
        Dim format As ImageFormat = ImageFormat.Gif
        Select Case extension.ToLower
            Case ".gif"
                format = ImageFormat.Gif
            Case ".jpg"
                format = ImageFormat.Jpeg
            Case ".jpeg"
                format = ImageFormat.Jpeg
            Case ".png"
                format = ImageFormat.Png
        End Select
        If format IsNot ImageFormat.Png Then
            Using b
                Dim quantizer As New OctreeQuantizer(255, 8)
                Using quantized As Bitmap = quantizer.Quantize(b)
                    Try
                        quantized.Save(Toolbox.TempPath & My.Settings.ImagePath & _imagename, format)
                    Catch ex As Exception
                        Dim x As Integer = 5
                    End Try

                End Using
            End Using
        Else
            b.Save(Toolbox.TempPath & My.Settings.ImagePath & _imagename, format)
        End If
        onImagingChanged(Me, New ImagingChangedEventArgs(Toolbox.TempPath & My.Settings.ImagePath & _imagename))
    End Sub
    Friend Function ExistsImage() As Boolean
        Return File.Exists(Toolbox.TempPath & My.Settings.ImagePath & _imagename)
    End Function
    Friend Sub SaveBytes(ByVal Bytes() As Byte, ByVal ImageName As String)
        File.WriteAllBytes(Toolbox.TempPath & My.Settings.ImagePath & ImageName, Bytes)
        onImagingChanged(Me, New ImagingChangedEventArgs(Toolbox.TempPath & My.Settings.ImagePath & ImageName))
    End Sub
    Friend Overrides Sub Execute()
        If ExistsImage() Then
            previousbytes = File.ReadAllBytes(Toolbox.TempPath & My.Settings.ImagePath & "\" & _imagename)
        End If
        ExecuteCommand()
    End Sub
    Friend Overrides Sub Undo()
        If previousbytes.Length <> 0 Then
            SaveBytes(previousbytes, _imagename)
        Else
            File.Delete(Toolbox.TempPath & My.Settings.ImagePath & "\" & _imagename)
        End If
    End Sub
End Class